package com.black.cat.seed.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.black.cat.seed.entity.*;
import com.black.cat.seed.mapper.UserMapper;
import com.black.cat.seed.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户表 服务实现类
 *
 * @author blackcat
 * @since 2020-07-21
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RolePermissionService rolePermissionService;

    @Override
    public List<Permission> getPermissions(Long userId) {
        //关联表信息
        QueryWrapper<UserRole> roleWrapper = new QueryWrapper();
        roleWrapper.lambda().eq(UserRole::getUserId, userId);
        List<UserRole> userRoles = userRoleService.list(roleWrapper);


        List<Long> roleIds = userRoles.stream()
                .map(UserRole::getRoleId)
                .collect(Collectors.toList());
        //角色信息
        List<Role> roles = roleService.listByIds(roleIds);

        QueryWrapper<RolePermission> permissionsWrapper = new QueryWrapper();
        permissionsWrapper.lambda().in(RolePermission::getRoleId, roleIds);
        List<RolePermission> rolePermissions = rolePermissionService.list(permissionsWrapper);
        List<Long> permissionIds = rolePermissions.stream()
                .map(RolePermission::getPermissionId)
                .collect(Collectors.toList());

        //权限信息
        List<Permission> permissions = permissionService.listByIds(permissionIds);
        return permissions;
    }
}
